// ==UserScript==
// @name         木讷拍牌助手
// @namespace    https://gitee.com/jiangmuhua/alltobid-helper.git
// @version      1.0.1
// @description  上海沪牌拍卖辅助工具，实现自动出价，自动提交
// @author       jmh_nt@qq.com
// @match        https://testh5.alltobid.com/*
// @match        https://paimai2.alltobid.com/*
// @match        https://paimai.alltobid.com/*
// @icon         https://www.alltobid.com/images/favicon.ico
// @license      MIT
// @require https://unpkg.com/jquery@3.6.0/dist/jquery.min.js
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @grant window.close
// @grant window.focus
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_setClipboard
// @grant GM_log
// ==/UserScript==

// debugger;
(function() {
    'use strict';

    // 日期克隆函数
    Date.prototype.clone=function(){
        return new Date(this.valueOf());
    }

    // 只能输入数字函数
    function onlyNumberKey(evt) {
        // Only ASCII character in that range allowed
        var ASCIICode = (evt.which) ? evt.which : evt.keyCode
        if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
            return false;
        return true;
    }

    // 设置React输入框变量函数
    function reactJSSetValue(elm, val) {
        if(elm.length == 0){
            return false;
        }
        let input = elm.get(0);
        let lastValue = input.value;
        input.value = val;
        let event = new Event('input', { bubbles: true });
        // hack React15
        event.simulated = true;
        let tracker = input._valueTracker;
        if (tracker) {
            tracker.setValue(lastValue);
        }
        input.dispatchEvent(event);
        return true;
    }

    let ct = document.createElement('div');
    ct.id = "sp-ac-container";
    ct.style.position="fixed"
    ct.style.left="10px"
    ct.style.top="10px"
    ct.style.padding="5px"
    ct.style.backgroundColor="#87CEFA"
    ct.style['z-index']="999999"
    ct.style.borderRadius="10px"
    ct.style.border="3px solid #73AD21"
    ct.innerHTML =`
    <div style="font-size:26px;font-weight:bold">木讷拍牌 v1.0.1</div>
    <table style="font-size:20px;font-weight: bold;border-collapse: separate;border-spacing: 3px 5px">
        <tr>
            <td>工具开关：</td>
            <td><input type="checkbox" id="cbx_switch" value="1" checked="true" style="-moz-transform: scale(1.8);-ms-transform: scale(1.8);-webkit-transform: scale(1.8);"/></td>
        </tr>
        <tr>
            <td>当前时间：</td>
            <td id="div_nowTime"></td>
        </tr>
        <tr>
            <td>出价时间：</td>
            <td id="div_execTime"></td>
        </tr>
        <tr>
            <td>出价倒计：</td>
            <td id="div_remainSec" style="color:red"></td>
        </tr>
        <tr>
            <td>强制提交：</td>
            <td><span id="dev_forceMin"></span><input type="number" id="txt_forceSec" style="font-size:22px;width:56px" value="55" maxLength="2" min="0" max="59" maxlength="2"/>
        </tr>
        <tr>
            <td>出价策略：</td>
            <td>
                <input type="number" id="txt_finalSec" min="0" max="59" style="font-size:22px;width:56px" value="45" maxlength="2"/>
                +
                <input type="number" min="300" max="1500" step="100" id="txt_finalAdd" style="font-size:22px;width:75px" value="1000" maxlength="4"/>
            </td>
        </tr>
        <tr>
            <td>提前出价：</td>
            <td>
              <select id="txt_aheadPrice" style="font-size:22px; width:65px">
                <option value="0">0</option>
                <option value="100">100</option>
                <option value="200">200</option>
                <option value="300">300</option>
              </select>
            </td>
        </tr>
        <tr>
            <td>最低价格：</td>
            <td id="div_minPrice" style="color:red"></td>
        </tr>
        <tr>
            <td>您的出价：</td>
            <td id="div_submitPrice" style="color:red"></td>
        </tr>
        <tr>
            <td colspan="2" style="color:red;text-align:center">&nbsp;<button id="btn_test" style="font-size:22px;display:none;">出价测试</button?</td>
        </tr>
        <tr>
            <td colspan="2" id="dev_checkStatus" style="color:#FF0000;background-color:yellow;text-align:center">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" style="color:red">
            tips:<br/>
            1. 请手动操作第一次出价！<br/>
            2. 验证码框会自动弹出来！<br/>
            3. 输验证码后记得按回车！<br/>
            4. 按回车键后什么都别碰！<br/>
            5. 最后10秒激活提前出价！<br/>
            </td>
        </tr>
    </table>
    `
    document.body.appendChild(ct);
    $('#txt_forceSec').keypress(onlyNumberKey);
    $('#txt_finalSec').keypress(onlyNumberKey);
    $('#txt_finalAdd').keypress(onlyNumberKey);
    // $(document).keydown(function(event){
    //     GM_log('你keydown：' + event.keyCode + ", event.target:" + event.target.nodeName + ", event.currentTarget:" + event.currentTarget.nodeName);
    // });

    var is_test = false;

    // 用于循环切换变量
    var mode_flag = false;

    // 开始执行Flag
    var execFlag = false;
    // 提交执行Flag
    var submitPrice = 0;
    // 回车键按下Flag
    var enterFlag = false;

    var sysDate = new Date();
    var y = sysDate.getFullYear();
    var m = sysDate.getMonth() + 1;
    var d = sysDate.getDate();
    var s_date = y + "-" + (m < 10 ? '0' + m : m) + "-" + (d < 10 ? '0' + d : d);
    var reMinPrice = /^\d{5,6}$/

    // $(document).ready(() => {
    // });
    $('#btn_test').click((event) => {
        is_test = true;
        GM_log('is_test1: ' + is_test);

        setTimeout(() => {
            is_test = false;
            GM_log('is_test2: ' + is_test);
        }, 1000);
    });

    var page_url = window.location.href;
    // GM_log(page_url);
    var isSimulate = page_url.startsWith("https://testh5.alltobid.com/")
    if(isSimulate){
        $('#dev_checkStatus').html("当前是模拟环境");
        $('#txt_aheadPrice').val("0");
    } else {
        $('#dev_checkStatus').html("当前是真实环境");
        $('#txt_aheadPrice').val("200");
    }

    // 默认最终时间
    var finalTime = new Date(s_date.trim() + " " + "11:30:00");

    setInterval(() => {

        let cbx_switch = $("#cbx_switch").is(':checked')
        if(!cbx_switch){
            $('#div_remainSec').html("自动出价已关闭");
            $('#btn_test').hide();
            // GM_log("工具关闭状态。");
            return;
        }
        $('#div_remainSec').html("");

        // ****************拍牌结束时间****************
        if (isSimulate) {
            let s_finalTime = $('.proinfo > span:nth-child(11) > span:nth-child(2)').text();
            if (!s_finalTime) {
                // GM_log("获取最终时间失败。");
                return;
            }

            // 最终时间
            finalTime = new Date(s_date + " " + s_finalTime + ":00");
        }

        // ****************当前系统时间****************
        let s_nowTime = $('.detail-proinfo > span:nth-child(4) > span:nth-child(1)').text();
        if(!s_nowTime){
            // GM_log("获取系统时间失败。");
            return;
        }

        let txt_finalSec = $('#txt_finalSec').val();
        let txt_finalAdd = $('#txt_finalAdd').val();
        let txt_aheadPrice = $('#txt_aheadPrice').val();
        let txt_forceSec = $('#txt_forceSec').val();
        // GM_log("----------------->>  " + txt_aheadPrice);
        if(!txt_aheadPrice){
            // 0 代表不提前出价
            txt_aheadPrice = "0";
        }

        if(!txt_forceSec){
            // 默认55秒强制提交
            txt_forceSec = "55";
        }

        // 最后50秒的时间
        let last50Time = finalTime.clone();
        last50Time.setMinutes(last50Time.getMinutes() - 1);
        last50Time.setSeconds(50, 0);

        // 执行时间
        let execTime = finalTime.clone();
        execTime.setMinutes(execTime.getMinutes() - 1);
        execTime.setSeconds(txt_finalSec, 0);

        // 强制提交时间
        let forceTime = finalTime.clone();
        forceTime.setMinutes(forceTime.getMinutes() - 1);
        forceTime.setSeconds(txt_forceSec, 0);

        // 当前时间
        let nowTime = new Date(s_date + " " + s_nowTime);

        // 剩余时间（秒）
        let remainSecond = (execTime - nowTime) / 1000;

        // 剩余强制提交时间（秒）
        let remainForceSecond = (forceTime - nowTime) / 1000;
        // GM_log("剩余强制提交时间（秒）:" + remainForceSecond);
        // GM_log("nowTime=" + nowTime + ", finalTime=" + finalTime + ", 还剩=" + remainSecond);

        $('#div_nowTime').html(nowTime.toLocaleTimeString());
        $('#div_execTime').html(execTime.toLocaleTimeString());
        $('#dev_forceMin').html(forceTime.toLocaleTimeString().substring(0, 6));

        // ****************第二阶段最低成交价****************
        let minPrice2 = $('.detail-proinfo > span:nth-child(6) > span:nth-child(1)').text();
        if(!minPrice2){
            // GM_log("获取最低成交价失败。");
            return;
        }

        if(!reMinPrice.test(minPrice2)){
            $('#div_remainSec').html("请手动出价");
            $('#btn_test').hide();
            return;
        }

        let tmpSubmitPrice = parseInt(minPrice2) + parseInt(txt_finalAdd);

        // **************** 第二三阶段 价格输入框 ****************
        if(!reactJSSetValue($('.whsetpriceinput'), tmpSubmitPrice)){
            $('#div_remainSec').html("手动出价时间段");
            $('#btn_test').hide();
            return;
        }

        $('#div_remainSec').html(remainSecond + " 秒");
        $('#div_minPrice').html(minPrice2);
        $('#btn_test').show();

        // **************** 第二三阶段 校验码输入框 ****************
        execFlag = ($('#bidprice').length > 0);
        // GM_log("execFlag = " + execFlag);
        if (!execFlag) {
            enterFlag = false;
            submitPrice = 0;
            $('#bidprice').unbind("keydown");

            $("body").css({
                backgroundColor: 'transparent',
            });
        }else{
            $('#bidprice').focus();
        }

        // 出价时间到达，开始执行出价
        if ((is_test || remainSecond == 0) && !execFlag) {

            // 此时此刻的出价获取
            submitPrice = tmpSubmitPrice;

            is_test = false;

            // **************** 第二三阶段 出价按钮按下 ****************
            $('.whsetpricebtn').click();

            $('#div_submitPrice').html(submitPrice);

            // **************** 第二三阶段 校验码输入框 ****************
            $('#bidprice').bind("keydown", (event) => {
                // GM_log('keydown：' + event.keyCode + ", event.target:" + event.target.nodeName + ", event.currentTarget:" + event.currentTarget.nodeName);
                if(event.keyCode == 13){
                    // 回车键按下标记True
                    enterFlag = true;
                    GM_log("按钮已按下");
                }
            });

            // 出价执行开始
            // execFlag = true;
        } else if(remainSecond < 0) {
            $('#div_remainSec').html(execFlag ? "正在出价…" : "出价完毕！");
        } else if(remainSecond > 0 && !enterFlag) {
            // $('#div_remainSec').html("请输验证码！");
        }

        // 出价完成&回车键按下 或者 强制提交时间到达
        if ((execFlag && enterFlag) || remainForceSecond == 0) {
            let execPrice = parseInt(minPrice2) + 300;

            // 最后的10秒激活提前出价功能，50秒之前，无法使用提前出价功能
            if (nowTime >= last50Time){
                // GM_log("提前出价激活！");
                execPrice = execPrice + parseInt(txt_aheadPrice);
            }

            if ((submitPrice > 0 && submitPrice <= execPrice) || remainForceSecond === 0) {
                GM_log("出价执行 出价:"+ submitPrice + ", 触发提交价格:" + execPrice + ", 剩余强制提交秒:" + remainForceSecond);

                // execFlag = false;
                enterFlag = false;
                submitPrice = 0;

                // **************** 第二三阶段 确认按钮 ****************
                $('.whpdConfirm').click();

                $('#div_remainSec').html("出价完毕！");
            } else {
                // var t = Math.floor((new Date()).getTime() / 100);
                $("body").css({
                    backgroundColor: mode_flag ? 'transparent' : 'red'
                });
                mode_flag = !mode_flag
            }
        }
    }, 100);

})();